package com.cjj.thread_safe;

class ThreadTrain5 implements Runnable {

    // 车票总数
    private static int count = 1000;

    private Object object = new Object();

    public boolean flag = true;

    @Override
    public void run() {
        // 如果flag 为true 先拿到object这把锁，再拿this锁
        if (flag) {
            while (count > 0) {
                synchronized (object) {
                    show();
                }
            }
        } else {
            while (count > 0) {
                show();
            }
        }

    }

    public synchronized void show() {
        synchronized (object){
            if (count > 0) {
                try {
                    Thread.sleep(40);
                } catch (Exception e) {

                }
                System.out.println(Thread.currentThread().getName() + "出售第" + (1000 - count + 1) + "张票");
                count--;
            }
        }
    }
}

/**
 * 死锁模拟
 *
 * @ClassName Thread_01
 * @Date 2021/07/17 11:23:43
 * @Created by ccc-j
 * @email ccc-ju@outlook.com
 */
public class Thread_05 {

    public static void main(String[] args) throws InterruptedException {
        // 创建两个线程, 线程类一定要是一个实例
        ThreadTrain5 threadTrain = new ThreadTrain5();
        Thread thread_1 = new Thread(threadTrain);
        Thread thread_2 = new Thread(threadTrain);
        thread_1.start();
        Thread.sleep(40);
        threadTrain.flag = false;
        thread_2.start();
    }

}
